package com.secneo.appshare.activities;

import java.text.MessageFormat;
import java.util.ArrayList;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView.OnItemClickListener;

import com.secneo.appshare.R;
import com.secneo.appshare.adapter.FeedsAdapter;
import com.secneo.appshare.api.LocalStore;
import com.secneo.appshare.api.RemoteApi.Feed;
import com.secneo.appshare.common.Constants;
import com.secneo.appshare.threads.GetAppusersThread;

public class ApplicationUsersActivity extends Activity {

	private GridView mGrid;
	private FeedsAdapter mAdapter;

	private String package_name;
	private int number;
	private String uid;
	private Boolean installed_not_addicted;

	private GetAppusersThread mGetAppUsersThread;

	private ProgressDialog mWaitDlg;

	private TextView mEmptyText;

	private String timeStamp;
	private boolean mDataComplete = false ; // 数据全部加在完毕
	private boolean mGetDataing = false ;
	private int mIntervalCount = 20 ;
	
	private ArrayList<Feed> userList ;

	public static boolean mRecyleFlag = false;

	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case Constants.MODE_GET_APP_USERS_FINISH:
				mGetDataing = false ;
				if (mWaitDlg != null && mWaitDlg.isShowing()) {
					mWaitDlg.dismiss();
				}
				if (mAdapter == null && mGetAppUsersThread.getUserInfo().userList.isEmpty()) {
					mEmptyText.setVisibility(View.VISIBLE);
				} else {
					if(mGetAppUsersThread.getUserInfo().userList.size() < mIntervalCount){
						mDataComplete = true ;
					}
					
					int count = mGetAppUsersThread.getUserInfo().userList.size() ;
					
					for(int i = 0 ; i < count ; ++i){
						userList.add(mGetAppUsersThread.getUserInfo().userList.get(i)) ;
					}
					
					timeStamp = mGetAppUsersThread.getUserInfo().timeStamp ;
					
					if(mAdapter == null){
						mAdapter = new FeedsAdapter(ApplicationUsersActivity.this
								.getApplicationContext(), userList);
						mGrid.setAdapter(mAdapter);
					} else {
						mAdapter.notifyDataSetChanged() ;
					}					
				}
				break;
			case Constants.MODE_GET_APP_USERS_NET_ERROR:
				if (mWaitDlg != null && mWaitDlg.isShowing()) {
					mWaitDlg.dismiss();
				}
				showNetworkErrView();
				break;
			case Constants.MSG_GET_APP_USERS_STATUS_ERROR:
				if (mWaitDlg != null && mWaitDlg.isShowing()) {
					mWaitDlg.dismiss();
				}
				break;
			case Constants.MSG_GET_APP_USERS_STATUS_OK:
				if (mWaitDlg != null && mWaitDlg.isShowing()) {
					mWaitDlg.dismiss();
				}
				break;
			case Constants.MODE_GET_APP_USERS_IMG_FINISH:
				mAdapter.notifyDataSetChanged();
				break;
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.appshare_app_users);

		parseIntent();

		mEmptyText = (TextView) findViewById(R.id.empty_tv);
		mGrid = (GridView) findViewById(R.id.app_user_grid);
		mGrid.setOnScrollListener(mScrollListner);
		mGrid.setOnItemClickListener(mOnItemClickListener) ;

		userList = new ArrayList<Feed>() ;
		
		timeStamp = MessageFormat.format("{0,date,yyyy-MM-dd HH:mm:ss}",
				new Object[] { new java.sql.Date(System.currentTimeMillis()) });
		mGetAppUsersThread = new GetAppusersThread(this, mHandler,
				package_name, number, uid, installed_not_addicted, mIntervalCount,
				timeStamp);
		mGetAppUsersThread.start();
		mGetDataing = true ;

		showDialog();
	}

	private void recycle(){
		if (mRecyleFlag) {
			// 回收资源
			mRecyleFlag = false;
			mGrid.setAdapter(null);
			if (mAdapter != null)
				mAdapter.freeDrawable();
			
			userList.clear() ;
			mAdapter = null ;
			mDataComplete = false ;
		}
	}
	
	@Override
	protected void onPause() {
		super.onPause();
		recycle() ;
	}

	
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		mRecyleFlag = false;
		mGrid.setAdapter(null);
		if (mAdapter != null)
			mAdapter.freeDrawable();
		
	}

	@Override
	protected void onNewIntent(Intent intent) {
		Boolean needInit = intent.getBooleanExtra("FromGroup", false);
		if (needInit) {
			timeStamp = MessageFormat
					.format("{0,date,yyyy-MM-dd HH:mm:ss}",
							new Object[] { new java.sql.Date(System
									.currentTimeMillis()) });
			mGetAppUsersThread = new GetAppusersThread(this, mHandler,
					package_name, number, uid, installed_not_addicted, mIntervalCount,
					timeStamp);
			mGetAppUsersThread.start();

			showDialog();
		}
		super.onNewIntent(intent);
	}

	private void showNetworkErrView() {
		if(mAdapter == null){
			View view = ApplicationUsersActivity.this.findViewById(R.id.error_user);
			view.setVisibility(View.VISIBLE);
		}
	}

	private void showDialog() {
		View view = ApplicationUsersActivity.this.findViewById(R.id.error_user);
		view.setVisibility(View.GONE);

		mWaitDlg = new ProgressDialog(this);
		String msg = getResources().getString(R.string.txt_loading);
		mWaitDlg.setMessage(msg);
		mWaitDlg.setCancelable(true);
		mWaitDlg.show();
	}

	private void parseIntent() {
		Bundle bundle = getIntent().getExtras();
		if (bundle != null) {
			package_name = bundle.getString("package_name");
			number = bundle.getInt("n", 20);
			uid = bundle.getString("uid");
			installed_not_addicted = bundle.getBoolean(
					"installed_not_addicted", true);
		}
	}

	private final OnItemClickListener mOnItemClickListener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			Intent intent = new Intent();
			intent.setClass(ApplicationUsersActivity.this, 
					AppsOtherUserActivity.class);

			Bundle mBundle = new Bundle();
			String uid = LocalStore.getLocaleStoreInstance(
					ApplicationUsersActivity.this).getUid();
			mBundle.putString("uid", uid);

			Feed feed = userList.get(position);
			mBundle.putString("other_uid", feed.uid);
			mBundle.putString("user_icon", feed.user_icon);
			mBundle.putString("user_name", feed.user_name);

			intent.putExtras(mBundle);
			startActivity(intent);
		}
		
	};
	
	private OnScrollListener mScrollListner = new OnScrollListener() {
		private int lastItem = 0;

		@Override
		public void onScroll(AbsListView view, int firstVisibleItem,
				int visibleItemCount, int totalItemCount) {
			lastItem = firstVisibleItem + visibleItemCount;
		}

		@Override
		public void onScrollStateChanged(AbsListView view, int scrollState) {
			if (mAdapter != null && lastItem == mAdapter.getCount()
					&& scrollState == OnScrollListener.SCROLL_STATE_IDLE) {
				if (mDataComplete)
					return;
				
				if(!mGetDataing){
					mWaitDlg = new ProgressDialog(ApplicationUsersActivity.this);
					String msg = getResources().getString(R.string.txt_loading);
					mWaitDlg.setMessage(msg);
					mWaitDlg.show();
					mGetAppUsersThread = new GetAppusersThread(ApplicationUsersActivity.this, mHandler,
							package_name, number, uid, installed_not_addicted, 20,
							timeStamp);
					mGetAppUsersThread.start();
					mGetDataing = true ;
				}
			}
		}
	};

}
